package com.sprite.support.wechat.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sprite.utils.UtilBeans;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sprite.support.wechat.bean.req.ReqBaseMessageBean;
import com.sprite.support.wechat.bean.req.ReqEventMessageBean;
import com.sprite.support.wechat.bean.resp.RespBaseMessageBean;
import com.sprite.support.wechat.common.WechatEventConstant;
import com.sprite.support.wechat.msghandler.EventMessageHandler;
import com.sprite.utils.UtilMisc;

/**
 * 微信时间分发器
 * @author Jack
 */
public final class WechatEventDispatcher extends EventMessageHandler{
	
	private static final Logger logger = LoggerFactory.getLogger(WechatEventDispatcher.class);
	
	public Map<String, WechatEventHandler<? super ReqEventMessageBean>> handlerMap =new HashMap<>();

	public <T extends ReqEventMessageBean> void setHandlers(List<WechatEventHandler<T>> handlers) {
		if(handlers != null) {
			for(WechatEventHandler<T> handler : handlers) {
				WechatEventHandler<? super ReqEventMessageBean>  eventHandler = UtilMisc.cast(handler);
				handlerMap.put(handler.eventType(), eventHandler);
			}
		}
	}

	@Override
	public RespBaseMessageBean handle(ReqEventMessageBean wechatMsg) {
		try {
			String eventKey = wechatMsg.getEvent();
			WechatEventHandler<? super ReqEventMessageBean> handler = handlerMap.get(eventKey);
			if(handler == null) {
				logger.info("[handle] not found handler, eventType:{}", eventKey);
				return null;
			}

			ReqEventMessageBean reqBaseMessageBean = UtilBeans.fromXml(wechatMsg.getMessageBody(), handler.eventBeanClass());

			return handler.handle(reqBaseMessageBean);
		} catch (Exception e) {
			logger.error("", e);
		}
		
		return null;
	}

}
